﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.DirectX.Direct3D;

namespace BurningSphere.Simulator.Controls
{
	/// <summary>
	/// Oscilating laser based on the MIDI notes coming through
	/// </summary>
	public class MidiFrequencyControl : MidiControlBase
	{
		float angle = 0.0f;
		float scale = 1.0f;
		int lastNote;
		int decayFrames = 100;
		int decay = 0;
		bool noteOn = false;

		/// <summary>
		/// Update
		/// </summary>
		/// <param name="matrix"></param>
		public override void Update(Microsoft.DirectX.Matrix matrix)
		{
			if (noteOn || decay > 0 )
			{
				angle += ((float)lastNote) / 128.0f;
				y = ((float)Math.Sin(Geometry.DegreeToRadian(angle)) * Scale);
				if( !noteOn ) decay--;
			}
			else
			{
				y = 0.0f;
			}

			base.Update(matrix);
		}

		/// <summary>
		/// Scale
		/// </summary>
		public float Scale
		{
			get
			{
				return scale;
			}
			set
			{
				scale = value;
			}
		}

		/// <summary>
		/// DecayFrames
		/// </summary>
		public int DecayFrames
		{
			get
			{
				return decayFrames;
			}
			set
			{
				decayFrames = value;
			}
		}

		/// <summary>
		/// Note on event
		/// </summary>
		/// <param name="note"></param>
		/// <param name="velocity"></param>
		protected override void OnNoteOn(int note, int velocity)
		{
			angle = 0.0f;
			lastNote = note;
			noteOn = true;
		}

		/// <summary>
		/// Note off event
		/// </summary>
		protected override void OnNoteOff()
		{
			noteOn = false;
			decay = decayFrames;
		}
	}
}
